package com.system.config;

import com.alibaba.fastjson.JSONObject;
import com.system.annotation.SystemLogAnnotation;
import com.system.config.jwt.JwtConfig;
import com.system.dao.SysLogDao;
import com.system.entity.manage.SysLog;
import com.system.entity.vo.RspResultVO;
import com.system.service.SystemService;
import com.system.utils.ExecutorUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 日志切面类
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private JwtConfig jwtConfig;
    @Autowired
    private SystemService systemService;

    private SysLog sysLog = new SysLog();

    /**
     * 功能描述: 切点
     */
    @Pointcut("@annotation(com.system.annotation.SystemLogAnnotation)")
    public void executePointCut() {
    }

    /**
     * 功能描述: 请求前执行
     */
    @Before("executePointCut()")
    public void doBefore(JoinPoint joinPoint)  {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //  操作时间
        sysLog.setCreateTime(new Date());
        //  接口地址
        sysLog.setReqUrl(request.getRequestURL().toString());
        //  接口名
        sysLog.setPackageName(joinPoint.getTarget().getClass().getName());
        //  接口方法
        sysLog.setMethodName(joinPoint.getSignature().getName());
        //  操作名称和业务类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLogAnnotation annotation = signature.getMethod().getAnnotation(SystemLogAnnotation.class);
        sysLog.setOperationName(annotation.operationName());
        sysLog.setBusinessType(annotation.businessType());
        //  请求参数
        sysLog.setReqParams("");
        //  请求ip
        sysLog.setIp(getRemoteHost(request));
        //  获取头部token
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            //  通过token获取用户对象
            String username = jwtConfig.getUsernameFromToken(token);
            //  操作人姓名
            sysLog.setUsername(username);
        }
        logger.info("请求日志========>>> ：{}", sysLog);
    }

    /**
     * 请求后执行
     */
    @AfterReturning(returning = "ret", pointcut = "executePointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        RspResultVO result = (RspResultVO) ret;
        sysLog.setRspCode(result.getCode());
        sysLog.setRspMsg(result.getMsg());
        //  方法结束时间
        sysLog.setEndTime(new Date());
        //  计算方法执行时间
        long executeTime = sysLog.getEndTime().getTime() - sysLog.getCreateTime().getTime();
        sysLog.setExecuteTime(executeTime);

        ExecutorUtil.submit(new Runnable() {
            @Override
            public void run() {
                systemService.saveSysLog(sysLog);
            }
        });
        logger.info(sysLog.getPackageName() + "." + sysLog.getMethodName() + " 请求耗时: {} ms", executeTime);
    }

    /**
     * 获取目标主机的ip
     *
     * @param request
     * @return
     */
    private String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }


}
